package com.china08.yxyapi;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.china08.yxyapi.model.YxyApiRespModel;

@RestController
@ControllerAdvice
public class YxyApiControllerAdvice {

    private final static Logger LOGGER = LoggerFactory.getLogger(YxyApiControllerAdvice.class);

    @ResponseBody
    @ExceptionHandler
    ResponseEntity<?> handleControllerException(HttpServletRequest request, Throwable ex) {
        String requestUri = request.getRequestURI();
        LOGGER.error("RequestUri:" + requestUri);
        HttpStatus status = getStatus(request);
        // ##
        // 处理Assert异常
        if (ex != null && ex instanceof IllegalArgumentException) {
            status = HttpStatus.UNPROCESSABLE_ENTITY;
            LOGGER.error("" + ex.getMessage());
        }
        // ##
        // 处理HttpRequestMethodNotSupportedException异常
        else if (ex != null && ex instanceof HttpRequestMethodNotSupportedException) {
            status = HttpStatus.METHOD_NOT_ALLOWED;
            LOGGER.error("" + ex.getMessage());
        }
        // ##
        // 处理NullPointerException异常
        else if (ex != null && ex instanceof NullPointerException) {
            // TODO 发送异常邮件通知
            LOGGER.error("", ex);
        }
        // ##
        // 处理其他异常
        else {
            // TODO 发送异常邮件通知
            LOGGER.error("", ex);
        }
        YxyApiRespModel respModel = new YxyApiRespModel();
        respModel.setMessage(ex.getMessage());
        return new ResponseEntity<>(respModel, status);
    }

    /**
     * HttpStatus.NOT_FOUND(404, "Not Found")
     * 
     * @param request
     * @param response
     * @param exception
     * @return
     */
    @RequestMapping(value = "/404")
    public ResponseEntity<?> error(HttpServletRequest request, Exception exception) {
        HttpStatus status = getStatus(request);
        String requestUri = (String) request.getAttribute("javax.servlet.error.request_uri");
        String msg = "Not Found Api:" + requestUri;
        YxyApiRespModel respModel = new YxyApiRespModel();
        respModel.setMessage(msg);
        return new ResponseEntity<>(respModel, status);
    }

    private HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        if (statusCode == null) { return HttpStatus.INTERNAL_SERVER_ERROR; }
        return HttpStatus.valueOf(statusCode);
    }
}
